from com.haohan.ipmi.ipmi import *
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] [Thread-%(thread)d] %(message)s')
logger = logging.getLogger()

# 连接PostgreSQL数据库
conn_params = {
    'dbname': db_name,
    'user': db_user,
    'password': db_passwd,
    'host': db_host,
    'port': db_port
}

def request_data(url):
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
    else:
        logger.error(f"请求失败，状态码: {response.status_code}")
        return {}

    # 解析响应数据
    if 'data' in data and 'result' in data['data']:
        return data['data']['result']
    else:
        logger.error("数据解析失败")
        return {}

def fetch2pg(ip_port):
    # 发送GET请求
    url1 = f"http://{ip_port}/api/v1/query?query=ipmi_dcmi_power_consumption_watts"
    now = datetime.datetime.now()
    timestamp = now.timestamp()
    formatted_time = now.strftime('%Y-%m-%d %H:%M:%S.%f')

    results = request_data(url1)
    # 记录数据条数
    logger.info(f"dcmi 方式获取到 {len(results)} 条数据")

    try:
        conn = psycopg2.connect(**conn_params)
        cursor = conn.cursor()

        # 准备批量插入的数据
        values = []
        for result in results:
            metric = result['metric']
            value = int(result['value'][1])
            values.append((metric['instance'], metric['rack'], value, int(timestamp), formatted_time, metric['department']))

        # 批量插入数据
        insert_query = """
        INSERT INTO dcmi_power_consumption_watts (instance, rack, power_value, time, event_time, department)
        VALUES (%s, %s, %s, %s, %s, %s)
        """
        cursor.executemany(insert_query, values)
        # 提交事务
        conn.commit()
        logger.info(f"成功插入 {len(values)} 条数据")
    except Exception as e:
        logger.error(f"数据库操作失败: {e}")
    finally:
        # 关闭连接
        cursor.close()
        conn.close()


def fetch2prometheus(ip_port):
    # 发送GET请求
    application_url = f'http://{ip_port}/api/v1/query?query=ipmi_power_watts' + '{name="Power",department="应用产品部"}'
    industry_url = f'http://{ip_port}/api/v1/query?query=ipmi_power_watts' + '{name=~"PS2 Input Power|Sys_Total_Power|Power",department="行业产品部",instance!="10.10.22.106"}'
    test_url = f'http://{ip_port}/api/v1/query?query=ipmi_power_watts' + '{name=~"Power",department="测试部"}'

    app = request_data(application_url)
    industry = request_data(industry_url)
    test = request_data(test_url)
    # 记录数据条数
    logger.info(f"ipmi_power_watts: app 方式获取到 {len(app)} 条数据")
    logger.info(f"ipmi_power_watts: industry 方式获取到 {len(industry)} 条数据")
    logger.info(f"ipmi_power_watts: test 方式获取到 {len(test)} 条数据")

    # 创建 Prometheus 指标注册表
    registry = CollectorRegistry()

    # 创建一个 Gauge 类型的指标
    power_gauge = Gauge('ipmi_dcmi_power_consumption_watts', 'IPMI Power Consumption in Watts',  ['instance', 'rack', 'department'], registry=registry)

    # 设置指标值
    for item in app + industry + test:
        metric = item['metric']
        # logger.info(f"{metric['instance']} {metric['rack']} {metric['department']} {item['value'][1]}")
        power_gauge.labels(metric['instance'], metric['rack'], metric['department']).set(item['value'][1])

    # 推送指标到 Pushgateway
    push_to_gateway('http://10.10.4.10:9091', job='ipmi_power', registry=registry)


def fetch2pg_task():
    while True:
        fetch2pg(prometheus_url)
        time.sleep(60)

def fetch2prometheus_task():
    while True:
        fetch2prometheus(prometheus_url)
        time.sleep(58)

if __name__ == "__main__":
    # 启动 fetch2pg 线程
    # fetch2pg_thread = threading.Thread(target=fetch2pg_task)
    # fetch2pg_thread.daemon = True
    # fetch2pg_thread.start()

    # 启动 fetch2prometheus 线程
    fetch2prometheus_thread = threading.Thread(target=fetch2prometheus_task)
    fetch2prometheus_thread.daemon = True  # 设置为守护线程，主程序退出时自动结束
    fetch2prometheus_thread.start()

    # 主程序保持运行
    while True:
        time.sleep(100)